﻿namespace IBTrader.Frontend.DailyTickData
{
    using IBTrader.Modules;
    using IBTrader.Modules.Configuration;
    using IBTrader.Modules.Log;
    using IBTrader.Properties;
    using Microsoft.Practices.Prism.Commands;
    using MvvmValidation;
    using NLog;
    using System;
    using System.Linq;
    using System.Windows;
    using System.Windows.Media;

    class ViewModel : ViewModelBase
    {
        private static readonly Logger logger = LogManager.GetCurrentClassLogger();
        public DelegateCommand Start { get; private set; }
        public ViewModel() : base(ComponentsSection.Components.DailyTickData)
        {
            Start = new DelegateCommand(OnStart);
            Validator.AddRule(() => RuleResult.Assert(Store.Contracts.Any(), "At least one contract must be configured"));
        }
        protected override void OnConnect()
        {
            if (IsValid())
                base.OnConnect();
        }
        private void OnStart()
        {
            if (IB.IsConnected())
                OnDisconnect();
            OnConnect();
        }
        #region update parent
        public void UpdateTitle(object _, ApplicationInfo.UpdateArgs e) // todo: move to parent?
        {
            this.view.Dispatcher.Invoke((Action)(() => W.X(logger, () =>
            {
                var parent = GetParentWindow(view) as Shell.View;
                if (parent != null)
                    parent.Title = e.Text;
            })));
        }
        public static Window GetParentWindow(DependencyObject child)
        {
            var parentObject = VisualTreeHelper.GetParent(child);

            if (parentObject == null)
            {
                return null;
            }

            var parent = parentObject as Window;
            if (parent != null)
            {
                return parent;
            }
            else
            {
                return GetParentWindow(parentObject);
            }
        }
        #endregion
        public override bool AutoConnect
        {
            get { return Settings.Default.LiveDataAutoConnect; }
            set 
            {
                Settings.Default.LiveDataAutoConnect = value;
                Settings.Default.Save();
            }
        }
    }
}